package com.system.service.sysuser.impl;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.common.core.constants.HttpConstants;
import com.common.core.domain.LoginUser;
import com.common.core.domain.R;
import com.common.core.domain.vo.LoginUserVO;
import com.common.core.enums.ResultCode;
import com.common.core.enums.UserIdentify;
import com.common.security.exception.ServiceException;
import com.common.security.service.TokenService;
import com.system.domain.sysUser.SysUser;
import com.system.domain.sysUser.dto.SysUserSaveDTO;
import com.system.mapper.sysuser.SysUserMapper;
import com.system.service.sysuser.ISysUserService;
import com.system.utils.BCryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@RefreshScope
@Service
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private TokenService tokenService;

    @Override
    public R<String> login(String userAccount, String password) {

        // 通过账号在数据库中查询用户信息
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper.lambda()
                        .select(SysUser::getUserId, SysUser::getPassword, SysUser::getNickName)
                        .eq(SysUser::getUserAccount, userAccount));
        if(sysUser == null){
            return R.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        if(BCryptUtils.matchPassword(password, sysUser.getPassword())){
            // 正式方案：先清除该用户的旧token，再创建新token，避免重复登录问题
            tokenService.deleteLoginUserByUserId(sysUser.getUserId(), secret);
            return R.success(tokenService.createToken(sysUser.getUserId(),
                    secret, UserIdentify.ADMIN.getValue(), sysUser.getNickName(), null));
        }
        return R.failed(ResultCode.FAILED_LOGIN);
    }

    @Override
    public boolean logout(String token) {
        if(!StrUtil.isEmpty(token) && token.startsWith(HttpConstants.PREFIX)){
            token = token.replace(HttpConstants.PREFIX,"");
        }
        return tokenService.deleteLoginUser(token, secret);
    }

    @Override
    public int add(SysUserSaveDTO sysUserSaveDTO) {
        List<SysUser> sysUserList = sysUserMapper.selectList(new QueryWrapper<SysUser>().lambda()
                .eq(SysUser::getUserAccount, sysUserSaveDTO.getUserAccount()));
        if(!CollectionUtils.isEmpty(sysUserList)){
            throw new ServiceException(ResultCode.ALTER_USER_EXISTS);
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserAccount(sysUserSaveDTO.getUserAccount());
        sysUser.setPassword(BCryptUtils.encryptPassword(sysUserSaveDTO.getPassword()));
        return sysUserMapper.insert(sysUser);
    }

    @Override
    public R<LoginUserVO> info(String token) {
        LoginUser loginUser = tokenService.getLoginUser(token, secret);
        if(loginUser == null){
            return R.failed();
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        loginUserVO.setNickName(loginUser.getNickName());
        return  R.success(loginUserVO);
    }
}
